﻿<%@ WebHandler Language="C#" Class="KMerWeb.Excel.GetHandler" %>

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using com.nm.library.Excels;
using com.nm.library.Excels.Enums;
using com.nm.library.Excels.mime;
using com.nm.library.Excels.Mef;
using com.nm.library.HttpHelper;

namespace KMerWeb.Excel
{
    /// <summary>
    /// Get请求
    /// </summary>
    public class GetHandler : BaseHttpHandler
    {
        public GetHandler()
        {
            base._httpReuqest = Context.Request.QueryString;
        }

        /// <summary>
        /// 下载模板文件
        /// </summary>
        /// <param name="context"></param>
        public void DownLoadTemplate()
        {
            var strType= _httpReuqest.Get("filetype").ToUpper();
            if (Context == null) return;
            if(AllImports==null)
                AllImports = MefConfig.ResolveMany<ExcelImport>();
            var type = EnumHelper.StringToEnum<ExcelImportType>(strType);
            var handler =AllImports.FirstOrDefault(e => e.Type == type);
            if (handler == null)
            {
                throw new Exception("未找到“" + type + "”相应处理模块");
            }
            var path = ExcelImporMapper.GetTemplatePath(type);
            if (File.Exists(path))
            {
                try
                {
                    //var filePath = Path.GetFileName(path);
                    Context.Response.Buffer = true;
                    Context.Response.Clear();
                    Context.Response.ContentType = MimeHelper.GetMineType(path);
                    var downFile = Path.GetFileName(path);
                    var encodeFileName = HttpUtility.UrlEncode(downFile, System.Text.Encoding.UTF8); //防止中文出现乱码
                    Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + encodeFileName + ";");
                    Context.Response.BinaryWrite(File.ReadAllBytes(path)); //返回文件数据给客户端下载
                    Context.Response.Flush();
                    Context.Response.End();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                throw new Exception("未找到“" + type + "”对应模版文件");
            }
        }
    }
}